package tom.client.invoice;

import tom.shared.InvItem;
import tom.shared.Stock;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.RadioButton;

public class StockPopup extends DialogBox {

	public static StockPopup popup = GWT.create(StockPopup.class);
	private VerticalPanel vPanel;
	private InvItem item;
	private CellTable<InvItem> table;

	public void setTable(CellTable<InvItem> table) {
		this.table = table;
	}

	public StockPopup() {
		this.setAnimationEnabled(true);
		this.setModal(true);
		this.setText("เลือกสต็อค");
		this.setWidth("200px");
		vPanel = new VerticalPanel();
		vPanel.setSpacing(5);
		this.setWidget(vPanel);
	}

	ClickHandler clickHandler = new ClickHandler() {
		@Override
		public void onClick(ClickEvent event) {
			item.stkCode = ((RadioButton) event.getSource()).getTitle();
			StockPopup.this.hide();
			table.redraw();
		}
	};

	KeyPressHandler keyHandler = new KeyPressHandler() {	
		@Override
		public void onKeyPress(KeyPressEvent event) {
			item.stkCode = ((RadioButton) event.getSource()).getTitle();
			StockPopup.this.hide();
			table.redraw();			
		}
	};
	
	public void open(InvItem item) {
		vPanel.clear();
		this.item = item;

		if (item.stocks != null && item.stocks.size() > 0) {
			for (int row = 0; row < item.stocks.size(); row++) {
				Stock stk = item.stocks.get(row);
				RadioButton button = new RadioButton("stock", stk.stkCode
						+ " คงเหลือ:" + stk.balance);
				button.addKeyPressHandler(keyHandler);
				button.setStyleName("popup");
				button.setTitle(stk.stkCode);
				button.addClickHandler(clickHandler);
				button.setValue(stk.stkCode.equals(item.stkCode));
				vPanel.add(button);
			}
			StockPopup.this.center();
		} else {
			Window.alert("No Stock!");
		}
		
	}
}
